package cc.cix.gt.org.controller;


import cc.cix.gt.common.exception.SystemException;
import cc.cix.gt.common.properties.MinIoProperties;
import cc.cix.gt.common.util.SystemUtil;
import cc.cix.gt.common.util.MinioUtil;
import cc.cix.gt.org.entity.File;
import cc.cix.gt.org.entity.User;
import cc.cix.gt.org.service.IFileService;
import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cix
 * @since 2022-06-04
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "文件上传管理")
@RequestMapping("/api/file")
public class FileController {

    private final MinIoProperties minIoProperties;
    private final IFileService fileService;

    @ApiOperation("上传文件")
    @PostMapping
    public List<File> upload(@RequestParam List<MultipartFile> files) {
        if (CollectionUtil.isEmpty(files)) {
            throw new SystemException("上传文件不能为空");
        }

        // 上传文件到 Minio
        MinioUtil.putObject(files, minIoProperties.getBucketName());

        // 将文件信息保存到数据库
        User user = SystemUtil.getCurrentUser();
        List<File> newFiles = new ArrayList<>();
        files.forEach(file -> {
            try {
                String url = minIoProperties.getUrl() + "/" + minIoProperties.getBucketName()
                        + '/' + file.getOriginalFilename();
                File newFile = new File();
                newFile.setUserId(user.getId());
                newFile.setUrl(url);
                newFile.setFileName(file.getOriginalFilename());
                newFile.setFileSize(file.getSize());
                newFile.setBucketName(minIoProperties.getBucketName());
                newFiles.add(newFile);
            } catch (Exception e) {
                throw new SystemException("生成访问链接失败");
            }
        });
        fileService.saveBatch(newFiles);
        return newFiles;
    }

    @ApiOperation("删除文件")
    @DeleteMapping("/{id}")
    public void delete(@PathVariable("id") String id) {
        try {
            File file = fileService.getById(id);
            MinioUtil.removeObject(file.getBucketName(), file.getFileName());
        } catch (Exception e) {
            log.error("文件删除失败：e={}", e.getMessage());
            throw new SystemException("删除失败");
        }
    }

}    

